package com.example.city_home_app.Activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.city_home_app.Bean.Down_Post;
import com.example.city_home_app.Bean.Down_PostComment;
import com.example.city_home_app.Bean.Down_Universe;
import com.example.city_home_app.Bean.PostContent;
import com.example.city_home_app.Model.ApiModel;
import com.example.city_home_app.R;
import com.example.city_home_app.RecyclerViewAdapter.Adapter_PostComment;
import com.example.city_home_app.RecyclerViewAdapter.Adapter_PostContent;
import com.example.city_home_app.RetrofitListener;
import com.example.city_home_app.UI.MyCircleImageView;
import com.example.city_home_app.UI.UIUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

import static com.example.city_home_app.Activity.PostAddActivity.cutStringByImgTag;

public class PostInfoActivity extends BaseActivity {
    @BindView(R.id.img_post_info_back)
    ImageView imgPostInfoBack;
    @BindView(R.id.img_post_info_headimage)
    MyCircleImageView imgPostInfoHeadimage;
    @BindView(R.id.tv_post_info_author)
    TextView tvPostInfoAuthor;
    @BindView(R.id.btn_post_info_focus)
    Button btnPostInfoFocus;
    @BindView(R.id.tv_post_info_title)
    TextView tvPostInfoTitle;
    @BindView(R.id.tv_post_info_time)
    TextView tvPostInfoTime;
    @BindView(R.id.rec_post_info_content)
    RecyclerView recPostInfoContent;
    @BindView(R.id.rec_post_info_comment)
    RecyclerView recPostInfoComment;
    @BindView(R.id.tv_post_info_commentcount)
    TextView tvPostInfoCommentcount;
    @BindView(R.id.btn_post_info_comment)
    Button btnPostInfoComment;
    @BindView(R.id.tv_post_info_likecount)
    TextView tvPostInfoLikecount;
    @BindView(R.id.img_post_info_like)
    ImageView imgPostInfoLike;
    @BindView(R.id.tv_post_info_comment)
    TextView tvPostInfoComment;
    @BindView(R.id.btn_post_info_del)
    Button btnPostInfoDel;

    private int postid, userid, likecount, commentcount, authoruserid;
    private ApiModel model = new ApiModel();
    private Adapter_PostContent adapter_postContent;
    private Adapter_PostComment adapter_postComment;
    private boolean isfocus, islike, isyourself = false;
    private BottomDialog dialog;
    private RetrofitListener<Down_Post> postRetrofitListener = new RetrofitListener<Down_Post>() {
        @Override
        public void onResponse(Down_Post listener) {
            authoruserid = listener.getUser_id();
            if(authoruserid == 0){
                btnPostInfoFocus.setVisibility(View.GONE);
            }
            if (userid == listener.getUser_id()) {
                isyourself = true;
                btnPostInfoFocus.setText("编辑");
                btnPostInfoDel.setVisibility(View.VISIBLE);
            }else{
                btnPostInfoDel.setVisibility(View.GONE);
            }
            tvPostInfoAuthor.setText(listener.getUser_name());
            commentcount = listener.getPost_comment();
            tvPostInfoCommentcount.setText("评论 " + listener.getPost_comment());
            likecount = listener.getPost_like();
            if (listener.getPost_like() == 0) {
                tvPostInfoLikecount.setVisibility(View.GONE);
            } else {
                tvPostInfoLikecount.setVisibility(View.VISIBLE);
            }
            tvPostInfoLikecount.setText("" + listener.getPost_like());
            tvPostInfoTime.setText(listener.getPost_time());
            tvPostInfoTitle.setText(listener.getPost_title());
            Picasso.with(PostInfoActivity.this)
                    .load("http://siminzhang.top:8088/city_home_server/public/static/posters/" + listener.getUser_headimage())
                    .into(imgPostInfoHeadimage);
            adapter_postContent.setList(resolveContent(listener.getPost_content()));
            adapter_postContent.notifyDataSetChanged();
        }

        @Override
        public void onFail(String msg) {

        }
    };

    private RetrofitListener<List<Down_PostComment>> commentlistRetrofitListener = new RetrofitListener<List<Down_PostComment>>() {
        @Override
        public void onResponse(List<Down_PostComment> listener) {
            if (listener.size() != 0) {
                tvPostInfoComment.setText("评论");
                adapter_postComment.setList(listener);
                adapter_postComment.notifyDataSetChanged();
            } else {
                tvPostInfoComment.setText("暂无评论");
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    private RetrofitListener<Down_Universe> upcommentlistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                UIUtils.showToast(PostInfoActivity.this, "评论成功", UIUtils.LENGTH_SHORT);
                model.getpostcomment(postid, commentlistRetrofitListener);
                tvPostInfoCommentcount.setText("评论 " + commentcount);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    private RetrofitListener<Down_Universe> delpostlistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            finish();
        }

        @Override
        public void onFail(String msg) {

        }
    };


    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_post_info;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ButterKnife.bind(this);


        recPostInfoContent = (RecyclerView) findViewById(R.id.rec_post_info_content);
        recPostInfoComment = (RecyclerView) findViewById(R.id.rec_post_info_comment);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        recPostInfoContent.setLayoutManager(layoutManager);
        recPostInfoComment.setLayoutManager(layoutManager2);
        adapter_postContent = new Adapter_PostContent(this);
        adapter_postComment = new Adapter_PostComment(this, getSupportFragmentManager());
        recPostInfoContent.setAdapter(adapter_postContent);
        recPostInfoComment.setAdapter(adapter_postComment);
        recPostInfoContent.setItemAnimator(new DefaultItemAnimator());
        recPostInfoComment.setItemAnimator(new DefaultItemAnimator());
        recPostInfoContent.setNestedScrollingEnabled(false);
        recPostInfoComment.setNestedScrollingEnabled(false);
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        postid = intent.getIntExtra("id", 0);
        userid = BaseActivity.getUserinfo().getUserid();
        model.getpostcomment(postid, commentlistRetrofitListener);
        model.isfocuspost(postid, userid, isfocusretrofitListener);
        model.islikepost(postid, userid, islikeretrofitListener);
    }


    @OnClick({R.id.img_post_info_back, R.id.img_post_info_headimage, R.id.tv_post_info_author, R.id.btn_post_info_focus, R.id.btn_post_info_comment,
            R.id.img_post_info_like,R.id.btn_post_info_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_post_info_back:
                finish();
                break;
            case R.id.img_post_info_headimage:
                Intent intent = new Intent(this, UserInfoActivity.class);
                intent.putExtra("id", authoruserid);
                startActivity(intent);
                break;
            case R.id.tv_post_info_author:
                break;
            case R.id.btn_post_info_focus:
                if (isyourself) {
                    //编辑界面
                    Intent intent2 = new Intent(this, PostAddActivity.class);
                    intent2.putExtra("type", 1);
                    intent2.putExtra("id", postid);
                    startActivity(intent2);
                } else {
                    if (isfocus) {
                        model.unfocuspost(postid, userid, unfocusretrofitListener);
                        isfocus = false;
                    } else {
                        model.focuspost(postid, userid, focusretrofitListener);
                        isfocus = true;
                    }
                }
                break;
            case R.id.btn_post_info_comment:
                dialog = BottomDialog.create(getSupportFragmentManager());
                dialog.setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(final View v) {
                        final EditText mEditText = (EditText) v.findViewById(R.id.edittext_dialog_newscomment_content);
                        Button button = (Button) v.findViewById(R.id.btn_dialog_newscomment_send);
                        mEditText.post(new Runnable() {
                            @Override
                            public void run() {
                                InputMethodManager imm =
                                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.showSoftInput(mEditText, 0);
                            }
                        });
                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (!mEditText.getText().toString().equals("")) {
                                    dialog.dismiss();
                                    model.uppostcomment(postid, userid, mEditText.getText().toString(), upcommentlistener);
                                } else {
                                    UIUtils.showToast(PostInfoActivity.this, "格式非法", UIUtils.LENGTH_SHORT);
                                }
                            }
                        });
                    }
                })
                        .setLayoutRes(R.layout.newscomment_dialog)
                        .setDimAmount(0.1f)
                        .setCancelOutside(true)
                        .setTag("评论")
                        .show();
                break;
            case R.id.img_post_info_like:
                if (islike) {
                    model.unlikespost(postid, userid, unlikeretrofitListener);
                    islike = false;
                } else {
                    model.likepost(postid, userid, likeretrofitListener);
                    islike = true;
                }
                break;
            case R.id.btn_post_info_del:
                deletepost();
            default:
        }
    }

    private void deletepost(){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("删除");
        normalDialog.setMessage("是否删除该帖子");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        model.delpost(postid,delpostlistener);
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        // 显示
        normalDialog.show();
    }

    private List<PostContent> resolveContent(String content) {
        List<PostContent> relist = new ArrayList<>();
        List<String> list = cutStringByImgTag(content);
        for (String s : list) {
            PostContent bean = new PostContent();
            if (s.startsWith("<img src=")) {
                Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher m_src = p_src.matcher(s);
                if (m_src.find()) {
                    String a = m_src.group(3);
                    s = a.replace("\\", "");
                    bean.setType(2);
                }
            } else {
                bean.setType(1);
            }
            bean.setContent(s);
            relist.add(bean);

        }
        return relist;
    }

    private RetrofitListener<Down_Universe> focusretrofitListener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                btnPostInfoFocus.setText("已关注");
                btnPostInfoFocus.setTextColor(0xff888888);
                isfocus = true;
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };
    private RetrofitListener<Down_Universe> unfocusretrofitListener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                btnPostInfoFocus.setText("关注");
                btnPostInfoFocus.setTextColor(0xffCD5C5C);
                isfocus = true;
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };
    private RetrofitListener<Down_Universe> isfocusretrofitListener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                btnPostInfoFocus.setText("已关注");
                btnPostInfoFocus.setTextColor(0xff888888);
                isfocus = true;
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };
    private RetrofitListener<Down_Universe> likeretrofitListener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                if (likecount == 0) {
                    tvPostInfoLikecount.setVisibility(View.VISIBLE);
                }
                imgPostInfoLike.setImageResource(R.drawable.ic_like);
                likecount++;
                tvPostInfoLikecount.setText("" + likecount);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };
    private RetrofitListener<Down_Universe> unlikeretrofitListener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                if (likecount == 1) {
                    tvPostInfoLikecount.setVisibility(View.GONE);
                }
                imgPostInfoLike.setImageResource(R.drawable.ic_like_no);
                likecount--;
                tvPostInfoLikecount.setText("" + likecount);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };
    private RetrofitListener<Down_Universe> islikeretrofitListener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                imgPostInfoLike.setImageResource(R.drawable.ic_like);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    @Override
    public void onResume() {
        super.onResume();
        model.getpost(postid, postRetrofitListener);
    }


}
